import { ref } from "vue";

export const useDragHook = (data, contentRef) => {
    const currentComponents = ref(null);
    // dragenter 进入元素的时候添加一个移动标识
    const dragEnter = (e) => {
        e.dataTransfer.dropEffect = "move";
    };
    // dragover 在目标元素经过 必须要阻止默认行为 否则不能触发drop 事件
    const dragOver = (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = "move";
    };
    // dragleave 离开元素时加一个禁用标识
    const dragLeave = (e) => {
        e.dataTransfer.dropEffect = "none";
    };
    // drop 鼠标松开的时候 根据拖拽的组件添加一个组件
    const drop = (e) => {
        const blocks = data.value.blocks;

        // 添加一个组件
        blocks.push({
            top: e.offsetY,
            left: e.offsetX,
            zIndex: 1,
            key: currentComponents.value.key,
            alignCenter: true,
            focus: false,
            props: {},
            model: {}
        });

        data.value = { ...data.value, blocks };

        currentComponents.value = null;
    };

    const dragStart = (e, component) => {
        contentRef.value.addEventListener("dragenter", dragEnter);
        contentRef.value.addEventListener("dragover", dragOver);
        contentRef.value.addEventListener("dragleave", dragLeave);
        contentRef.value.addEventListener("drop", drop);
        currentComponents.value = component;
    };

    // 取消所有的监听
    const dragEnd = () => {
        contentRef.value.removeEventListener("dragenter", dragEnter);
        contentRef.value.removeEventListener("dragover", dragOver);
        contentRef.value.removeEventListener("dragleave", dragLeave);
        contentRef.value.removeEventListener("drop", drop);
    };

    return { dragStart, dragEnd };
};
